<template>
  <div id="app">
    <Dialog ref="dialog" />

    <the-header v-if="headerVisible && $route.path === '/'" />
    <menu-bar
      v-if="menuVisible"
      class="mb"
      :menus="menus"
      :current-path="currentPath"
      :tabs-class="tabsClass"
    />
    <div class="main">
      <router-view></router-view>
    </div>
    <van-tabbar v-if="$route.path === '/'">
      <van-tabbar-item icon="home-o">
        <template #icon="props">
          <i class="iconfont icon-shouyeweixuanzhong"></i>
        </template>
        首页
      </van-tabbar-item>
      <van-tabbar-item icon="search">
        <template #icon="props">
          <i class="iconfont icon-fenquweixuanzhong"></i>
        </template>
        频道
      </van-tabbar-item>
      <van-tabbar-item icon="friends-o" badge="27">
        <template #icon="props">
          <i class="iconfont icon-dongtaiweixuanzhong"></i>
        </template>
        动态
      </van-tabbar-item>
      <van-tabbar-item icon="setting-o">
        <template #icon="props">
          <i class="iconfont icon-1672fu"></i>
        </template>
        会员购
      </van-tabbar-item>
      <van-tabbar-item icon="setting-o">
        <template #icon="props">
          <i class="iconfont icon-wodeweixuanzhong"></i>
        </template>
        我的
      </van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
import TheHeader from "@/components/the-header/TheHeader.vue";
import MenuBar from "@/components/menu-bar/MenuBar.vue";
import config from "@/router/config.js";
import Dialog from "@/views/dialog";

export default {
  name: "App",
  provide() {
    return {
      rootThemeColor: "#fb7299",
      rootRouter: this.$router,
      routerConfig: config,
      rootTitle: "哔哩哔哩 (゜-゜)つロ 干杯~-bilibili",
      rootKeyword:
        "B站,bilibili,哔哩哔哩,哔哩哔哩动画,动漫,电影,在线动漫,高清电影",
      rootDescription:
        "bilibili是国内知名的在线视频弹幕网站，拥有最棒的ACG氛围，哔哩哔哩内容丰富多元，涵盖动漫、电影、二次元舞蹈视频、在线音乐、娱乐时尚、科技生活、鬼畜视频等。下载客户端还可离线下载电影、动漫。",
      rootSend: this.send
    };
  },
  components: {
    TheHeader,
    MenuBar,
    Dialog
  },
  data() {
    return {
      tabsClass: "top-menu-bar",
      currentPath: "/",
      headerVisible: true,
      menuVisible: true,
      myWebsocket: null,
      seriaFlag: false
    };
  },
  computed: {
    menus() {
      const arr = [
        {
          title: "直播",
          path: ""
        },
        {
          title: "推荐",
          path: "/"
        },
        {
          title: "热门",
          path: ""
        },
        {
          title: "追番",
          path: ""
        },
        {
          title: "视频",
          path: ""
        }
      ];
      /* for (const c of config) {
        const { name, tid, route, hide } = c
        if (hide) {
          continue
        }
        arr.push({
          title: name,
          path: route === '/' ? route : `/channel/${tid}`
        })
      } */
      return arr;
    }
  },

  watch: {
    $route(to) {
      if (to.name === "index") {
        sessionStorage.messageType = 0;
      } else {
        sessionStorage.messageType = 1;
      }
      const {
        meta: { headerVisible, menuVisible }
      } = to;
      this.headerVisible = headerVisible;
      this.menuVisible = menuVisible;
      this.menuVisible && this.setCurrentPath(to);
    }
  },
  created() {
    this.menuVisible && this.setCurrentPath(this.$route);
  },
  async mounted() {
    await this.$nextTick();
    /* const query = this.$route.query;
    const dataArr = ["a", "b", "c", "d"];
    const dataNum = [1, 2, 3, 4];
    let index = 0;
    if (query.id && dataArr.includes(query.id)) {
      index = dataArr.indexOf(query.id);
    } */

    this.socket();
    /*  setTimeout(() => {
      this.send({
        type: sessionStorage.dataNum
      });
    }, 1000); */
  },
  methods: {
    socket(e) {
      console.log(e);
      this.myWebsocket = new WebSocket(APP_SERVER_SOCKET);
      // 连接发生错误的回调方法
      this.myWebsocket.onerror = () => {
        console.log("WebSocket连接发生错误");
        this.myWebsocket = new WebSocket(APP_SERVER_SOCKET);
      };
      // 连接成功建立的回调方法
      this.myWebsocket.onopen = e => {
        console.log("WebSocket连接成功");
        const obj = {
          messageType: sessionStorage.messageType,
          type: sessionStorage.dataNum
        };
        this.send(obj);
        setInterval(() => {
          this.send({ messageType: 9999 });
        }, 3000);
      };
      // 接收到消息的回调方法
      this.myWebsocket.onmessage = event => {
        let data = {};
        if (event.data) {
          try {
            data = JSON.parse(event.data);
          } catch (err) {
            console.log(err);
          }
          console.log(data);
          if (data.serialNumber && !this.seriaFlag) {
            this.seriaFlag = true;
            this.$refs.dialog.open(data.serialNumber);
          }
        }
      };
      // 连接关闭的回调方法
      this.myWebsocket.onclose = function() {
        console.log("webSocket连接关闭！");
      };
      // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
      window.onbeforeunload = function() {
        closeWebSocket();
      };

      // 关闭WebSocket连接
      function closeWebSocket() {
        this.myWebsocket.close();
      }
    },
    send(obj) {
      if (!window.WebSocket) {
        return;
      }
      if (this.myWebsocket.readyState == WebSocket.OPEN) {
        this.myWebsocket.send(JSON.stringify(obj));
      }
    },

    matchPath(id) {
      return config.findIndex(c => c.tid === id);
    },
    setCurrentPath(route) {
      const {
        path,
        params: { id, subid }
      } = route;
      if (!id && !subid) {
        if (path === "/") {
          this.currentPath = path;
        } else {
          this.$router.replace({ name: "404" });
        }
      } else {
        const match = this.matchPath(id - 0);
        if (match === -1) {
          this.$router.replace({ name: "404" });
        } else {
          if (id && subid) {
            this.currentPath = `/channel/${id}`;
          } else {
            this.currentPath = path;
          }
        }
      }
    }
  }
};
</script>

<style lang="scss">
@import url("//at.alicdn.com/t/font_1759261_blj44qlo8ih.css");
@import "~normalize.css";
@import url("//at.alicdn.com/t/font_2380035_d8usaz0blpk.css");
@import "@/styles/global.scss";
</style>
<style lang="scss" scoped>
.mb {
  position: sticky;
  top: rem(44px);
  z-index: 99;
}
.top-menu-bar ::v-deep .van-tab {
  flex-basis: 100/6.5 * 1% !important;
}
.main {
  background: #f4f4f4;
  // padding-top: rem(6px);
}
.van-tabbar-item {
  .iconfont {
    font-size: rem(18px);
    font-weight: 999;
  }
}
.van-tabbar-item--active {
  color: #e87697;
}
</style>
